package com.cmwa.scbp.sys.userInfo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.scbp.base.mvc.controller.BaseController;
import com.cmwa.scbp.base.mvc.entity.Page;
import com.cmwa.scbp.base.mvc.entity.Result;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.sys.menu.entity.TreeElem;
import com.cmwa.scbp.sys.organization.entity.OrganizationVo;
import com.cmwa.scbp.sys.organization.service.OrganizationService;
import com.cmwa.scbp.sys.userInfo.entity.UserInfoVo;
import com.cmwa.scbp.sys.userInfo.service.UserInfoService;
import com.cmwa.scbp.base.constants.Constant;
import com.cmwa.scbp.utils.PinYinUtil;
import com.cmwa.scbp.utils.PwdUtil;
import com.cmwa.scbp.utils.Utils;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/sys/user")
public class UserInfoController extends BaseController {

	private final static String PAGE_PATH = "system/sys/user/";
	@Resource
	private OrganizationService organizationService;
	@Resource
	private UserInfoService userInfoService;


	/**
	 * 用户管理页面
	 * @author ex-hejm
	 * @date 2019年2月19日上午9:17:55
	 * @param model
	 * @return
	 */
	@RequestMapping("/userListView")
	public String userListView(ModelMap model) {
		return PAGE_PATH + "userList";
	}
	
	@RequestMapping("/modifyPwdView")
	public String modifyPwdView(ModelMap model) {
		return PAGE_PATH + "modifyPwd";
	}
	
	/**
	 * 外部人员新增页面
	 * @author ex-hejm
	 * @date 2019年2月19日下午4:25:03
	 * @param model
	 * @return
	 */
	@RequestMapping("/outUserAddView")
	public String outUserAddView(ModelMap model) {

		List<OrganizationVo> orgTree = organizationService.queryOrgTreeList();
		model.put("orgTree", orgTree);
		
		return PAGE_PATH + "outUserAdd";
	}
	
	@RequestMapping("/modifyPassword")
	@ResponseBody
	public Result<Object> modifyPassword(@RequestParam("empId") String empId, @RequestParam("login") String login, @RequestParam("password") String password) {

		Result<Object> result = new Result<Object>();
		
		userInfoService.modifyPassword(empId, login, password);

		result.setSuccess(true);

		return result;
	}
	
	/**
	 * 验证重复账号
	 * @author ex-hejm
	 * @date 2019年2月20日下午2:37:37
	 * @param login
	 * @return
	 */
	@RequestMapping("/checkRepeatLogin")
	@ResponseBody
	public Result<Object> checkRepeatLogin(@RequestParam("login") String login) {
		boolean isRepeat = userInfoService.checkRepeatLogin(login);
		Result<Object> result = new Result<Object>();
		result.setSuccess(isRepeat);
		return result;
	}

	/**
	 * 更改员工状态
	 * @author ex-hejm
	 * @date 2019年2月20日下午6:00:38
	 * @param empId
	 * @param stat
	 * @return
	 */
	@RequestMapping("/changeEmpStat")
	@ResponseBody
	public Result<Object> changeEmpStat(@RequestParam("empId") String empId, @RequestParam("stat") String stat) {
		Result<Object> result = new Result<Object>();
		userInfoService.changeEmpStat(empId, stat);
		return result;
	}
	
	/**
	 * 验证旧密码
	 * @author ex-hejm
	 * @date 2019年2月20日下午2:37:43
	 * @param login
	 * @return
	 */
	@RequestMapping("/checkOldPassword")
	@ResponseBody
	public Result<Object> checkOldPassword(@RequestParam("empId") String empId, @RequestParam("password") String password) {
		
		UserInfoVo user = userInfoService.getUserInfoById(empId);
		
		// 对用户填的密码进行加密
		PwdUtil encoderMd5 = new PwdUtil(user.getLogin(), PwdUtil.STRATEGY_MD5);
		String encodePwd = encoderMd5.encode(password);
		
		// 用加密后的密码跟数据库的密码比对
		boolean equals = StringUtils.equals(encodePwd, user.getPassword());
		Result<Object> result = new Result<Object>();
		result.setSuccess(equals);
		return result;
	}
	
	@RequestMapping("/generateLogin")
	@ResponseBody
	public Result<Object> generateLogin(@RequestParam("emName") String emName) throws Exception {
		
		String emNamePinYin = PinYinUtil.getPinYinFS(emName);
		
		UserInfoVo user = userInfoService.getUserInfoLogin(emNamePinYin);
		if(user != null) {
			String login = user.getLogin();
			emNamePinYin = Utils.generateCodePinyinStr(login);
		}
		Result<Object> result = new Result<Object>();
		result.setObject(emNamePinYin);
		return result;
	}
	
	/**
	 * 新增外部人员
	 * @author ex-hejm
	 * @date 2019年2月19日下午6:30:43
	 * @param user
	 * @return
	 */
	@RequestMapping("/insertOutUser")
	public String insertOutUser(UserInfoVo user) {
		userInfoService.insertOutUser(user);
		return redirectSuccess();
	}
	
	@RequestMapping("/userListPage")
	@ResponseBody
	public Page<UserInfoVo> userListPage(SearchParam sp) {
		Page<UserInfoVo> list = userInfoService.userListPage(sp);
		return list;
	}
	
	/**
	 * 部门树
	 * @author ex-hejm
	 * @date 2019年2月19日上午9:45:47
	 * @param orgId
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/ajaxOrganizationList")
	public void ajaxOrganizationList(@RequestParam("orgId") String orgId, HttpServletResponse response) throws IOException {
		List<TreeElem> elems = new ArrayList<TreeElem>();

		if (!orgId.startsWith(Constant.USERTREE_STATION_PREFIX)) {
			
			if(orgId.startsWith(Constant.USERTREE_FIRM_PREFIX)) {
				String[] orgIds = orgId.substring(Constant.USERTREE_FIRM_PREFIX.length()).split(Constant.USERTREE_SPILT);
				orgId = orgIds[0];
			}
			
			
			// 根据组织的父ID查询子列表，根节点的父节点为空
			List<OrganizationVo> list = organizationService.queryOrganizationListByParentId(orgId);
			for (OrganizationVo vo : list) {
				TreeElem elem = new TreeElem();
				elem.getState();
				
				if (StringUtils.isBlank(orgId)) {
					elem.setId(Constant.USERTREE_FIRM_PREFIX + vo.getOrgId() + Constant.USERTREE_SPILT + vo.getOrgType());
				} else {
					elem.setId(vo.getOrgId());
				}
				
				elem.setText(vo.getOrgName());
				elems.add(elem);
			}

			// 根据组织ID查询岗位列表
			if (StringUtils.isNotBlank(orgId)) {
				List<OrganizationVo> list2 = organizationService.queryStationListByOrgId(orgId);
				for (OrganizationVo vo : list2) {
					TreeElem elem = new TreeElem();
					elem.setId(Constant.USERTREE_STATION_PREFIX + orgId + Constant.USERTREE_SPILT + vo.getTitleId());
					elem.setText(vo.getTitleName());
					elems.add(elem);
				}
			}
		}

		// 根据岗位ID查询成员列表
		if (StringUtils.isNotBlank(orgId) && orgId.startsWith(Constant.USERTREE_STATION_PREFIX)) {
			String[] orgIds = orgId.substring(Constant.USERTREE_STATION_PREFIX.length()).split(Constant.USERTREE_SPILT);
			String orgIdx = orgIds[0];
			String stationId = orgIds[1];
			List<UserInfoVo> userList = userInfoService.queryEmpListByStationId(orgIdx, stationId);
			for (UserInfoVo vo : userList) {
				TreeElem elem = new TreeElem();
				elem.getState().setLoaded(true).setOpened(true);
				elem.setId(Constant.USERTREE_EMP_PREFIX + vo.getEmpID());
				elem.setText(vo.getEmpName());
				elems.add(elem);
			}
		}

		PrintWriter out = response.getWriter();
		response.setContentType("application/json;charset=UTF-8");
		out.write(JSONArray.fromObject(elems).toString());
	}
}
